<template>
    <div>
        <back-head title="虚拟充值商品列表"></back-head>
        <!-- 搜索条件 -->
        <el-card class="mgb20" shadow="hover">
            <div slot="header" class="clearfix">
                <span>筛选查询</span>
            </div>
            <el-form :inline="true" :model="searchData" ref="ruleForm" label-width="90px" :rules="rules">
                <el-form-item label="商品编号：" prop="id">
                    <el-input 
                        v-model="searchData.id"
                        placeholder="请输入商品编号"
                        style="width: 150px;margin-right: 20px;">
                    </el-input>
                </el-form-item>
                <el-form-item label="商品名称：" prop="name">
                    <el-input 
                        v-model="searchData.name"
                        placeholder="请输入商品名称"
                        style="width: 150px;margin-right: 20px;">
                    </el-input>
                </el-form-item>
                <el-form-item label="商品所属：" prop="belong">
                    <el-select v-model="searchData.belong" style="width: 130px;margin-right: 5px;">
                        <el-option value="" label="全部"></el-option>
                        <el-option
                            v-for="(value, key) in searchData.belongList"
                            :key="key"
                            :label="value"
                            :value="key">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品状态：" prop="status">
                    <el-select v-model="searchData.status" style="width: 130px;margin-right: 5px;">
                        <el-option value="" label="全部"></el-option>
                        <el-option
                            v-for="(value, key) in searchData.statusList"
                            :key="key"
                            :label="value"
                            :value="key">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="创建时间：" prop="createTime">
                    <el-date-picker
                        v-model="searchData.createTime"
                        type="datetimerange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        :picker-options="searchData.pickerOptions"
                        class="datetimerange"
                        >
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="状态更新时间：" prop="updateTime" label-width="110px">
                    <el-date-picker
                        v-model="searchData.updateTime"
                        type="datetimerange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        :picker-options="searchData.pickerOptions"
                        class="datetimerange"
                        >
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="submitForm('ruleForm')">查询</el-button>
                    <el-button type="primary" icon="el-icon-refresh" @click="resetForm('ruleForm')">重置</el-button>
                    <el-button type="warning" icon="el-icon-lx-warn" v-if="oneStatus == 2" @click="updateAll(1)">一键恢复</el-button>
                    <el-button type="warning" icon="el-icon-lx-warn" v-if="oneStatus == 1" @click="updateAll(2)">一键下架</el-button>
                    <el-button type="warning" icon="el-icon-lx-warn" v-if="oneStatus !== 1&&oneStatus !== 2" :disabled="oneStatus !== 1&&oneStatus !== 2">一键下架</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 数据列表 -->
        <el-card class="mgb20" shadow="hover">
            <div slot="header" class="clearfix">
                <span>数据列表</span>
                <el-button type="success" size="small" icon="el-icon-lx-roundadd" @click="editInfo(0)" class="createBtn">创建商品</el-button>
            </div>
            <el-row>
                <el-table
                    ref="list"
                    border
                    :data="dataList"
                    highlight-current-row
                    style="width: 100%;">
                    <el-table-column
                        label="选择"
                        width="60">
                        <template slot-scope="scope">
                            <el-checkbox-group v-model="checkedData" @change="handleSelectionChange">
                                <el-checkbox :label="scope.row.id">
                                    <span style="display: none;"></span>
                                </el-checkbox>
                            </el-checkbox-group>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="id"
                        label="商品编号">
                    </el-table-column>
                    <el-table-column
                        prop="code"
                        label="第三方商品编号">
                    </el-table-column>
                    <el-table-column
                        prop="belong"
                        label="商品所属">
                        <template slot-scope="scope">
                            {{searchData.belongList[scope.row.belong] || '未知'}}
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="name"
                        label="商品名称"
                        show-overflow-tooltip
                        width="200">
                    </el-table-column>
                    <el-table-column
                        min-width="90"
                        label="商品成本价">
                        <template slot-scope="scope">
                            ￥ {{scope.row.shopMoney | toFixed2}}
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="商品售价">
                        <template slot-scope="scope">
                            ￥ {{scope.row.salePrice | toFixed2}}
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="商品状态">
                        <template slot-scope="scope">
                            {{searchData.statusList[scope.row.status] || '未知'}}
                        </template>
                    </el-table-column>
                    <el-table-column
                        min-width="150"
                        label="创建时间">
                        <template slot-scope="scope">
                            {{scope.row.createTime | formatDate}}
                        </template>
                    </el-table-column>
                    <el-table-column
                        min-width="150"
                        label="状态更新时间">
                        <template slot-scope="scope">
                            {{scope.row.updateTime | formatDate}}
                        </template>
                    </el-table-column>
                    <el-table-column
                        fixed="right"
                        label="操作"
                        width="110">
                        <template slot-scope="scope">
                            <el-button type="text" icon="el-icon-edit" @click="editInfo(1,scope.row)">更改信息</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column
                        fixed="right"
                        label="商品状态编辑"
                        width="110">
                        <template slot-scope="scope">
                            <el-button type="text" @click="operationBtn(scope.row.id,1)" :disabled='oneStatus==2 || scope.row.status == 1'>上架</el-button>/
                            <el-button type="text" @click="operationBtn(scope.row.id,2)" :disabled='oneStatus==2 || scope.row.status == 2' style="margin-left: 0">下架</el-button>
                            <br>
                            <el-button type="text" @click="operationBtn(scope.row.id,3)" :disabled='oneStatus==2 || scope.row.status == 3'>库存不足</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column
                        fixed="right"
                        label="归属城市"
                        width="110">
                        <template slot-scope="scope">
                            <el-button v-if="scope.row.flag" type="text" icon="el-icon-reading" @click="checkArea(scope.row.id)">查看</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-row>
        </el-card>

        <el-card class="mgb20" shadow="hover">
            <el-row>
                <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">当页全选</el-checkbox>
                <el-select v-model="operationType" style="width: 130px;margin-right: 15px;">
                    <el-option label="批量下架" value="2"></el-option>
                    <el-option label="批量上架" value="1"></el-option>
                </el-select>
                <el-button @click="operationBtn(checkedData,operationType)">确定</el-button>
                <el-pagination
                    @current-change="getData"
                    :current-page.sync="current"
                    :page-size="pageSize"
                    layout="total, prev, pager, next, jumper"
                    v-if="total > 0"
                    style="float:right"
                    :total="total">
                </el-pagination>
            </el-row>
        </el-card>

        <el-dialog :title="editType == 0? '创建商品':'更改信息'" :visible.sync="dialogFormVisible" width="500px" @close="closeEdit" v-dialogDrag>
            <el-form 
                :model="editForm" 
                :rules="rulesEdit" 
                label-width="110px" 
                @keyup.enter.native="submitEdit('ruleEditForm')" 
                ref="ruleEditForm">
                <el-form-item label="商品编号：" v-if="editType == 0" prop="code">
                    <el-input v-model="editForm.code" class="dialogInput" placeholder="请输入商品编号"></el-input>
                </el-form-item>
                <el-form-item label="商品名称：" prop="name">
                    <el-input v-model="editForm.name" class="dialogInput" placeholder="请输入商品名称"></el-input>
                </el-form-item>
                <el-form-item label="商品成本价：" prop="shopMoney">
                    <el-input v-model="editForm.shopMoney" class="dialogInput" placeholder="请输入商品成本价"></el-input>
                </el-form-item>
                <el-form-item label="商品售价：" prop="salePrice">
                    <el-input v-model="editForm.salePrice" class="dialogInput" placeholder="请输入商品售价"></el-input>
                </el-form-item>
                <el-form-item label="商品所属：" prop="belong">
                    <el-select v-model.number="editForm.belong" class="dialogInput" placeholder="请选择">
                        <el-option
                            v-for="(value, key) in searchData.belongList"
                            :key="key"
                            :label="value"
                            :value="Number(key)">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitEdit('ruleEditForm')">保 存</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>        
    export default {
        name: 'orderList',
        data() {
            let checkNum = (rule, value, callback)=>{
                if(value ==''){
                    callback();
                }
                if(!this.util.RegExpr.checkNum(value)){
                    callback(new Error('此字段只支持数字'));
                }else{
                    callback();
                }
            };
            let checkPrice = (rule, value, callback)=>{
                if(!this.util.RegExpr.checkPrice(value)){
                    callback(new Error('请输入正确的价格'))
                }else{
                    callback();
                }
            }
            return {
                rules: {
                    orderId: [
                        { validator: checkNum, trigger: 'blur', require : false}
                    ],
                    id: [
                        { validator: checkNum, trigger: 'blur', require : false}
                    ]
                },
                rulesEdit: {
                    name : [{ required: true, message: '请输入商品名称', trigger: 'blur'}],
                    // code : [{ required: true, message: '请输入商品编号', trigger: 'blur'}],
                    shopMoney : [{ required: true, message: '请输入商品成本价', trigger: 'blur', validator: checkPrice}],
                    salePrice : [{ required: true, message: '请输入商品售价', trigger: 'blur', validator: checkPrice}],
                    belong : [{ required: true, message: '请输入商品所属', trigger: 'blur'}]
                },
                searchData : {
                    id: '',
                    name: '',
                    belong: '',
                    belongList:{
                        1 : '欧飞',
                        2 : '拉卡拉',
                        3 : '雪虎'
                    },
                    status: '',
                    statusList: {
                        1 : '上架',
                        2 : '下架',
                        3 : '库存不足',
                        // 4 : '系统维护'
                    },
                    createTime: '',
                    updateTime: '',
                    pickerOptions: {
                        disabledDate: (time)=>{
                            return time.getTime() > Date.now();
                        }
                    }
                },
                oneStatus:1,
                dataList : [],    //list数据
                checkAll: false,
                isIndeterminate: false,
                checkedGameId : [], //所有数据的id集合
                checkedData : [],   //当前选中的数据id集合
                operationType: '2',
                current : 1,  //当前页码
                pageSize : Number(localStorage.getItem('pageSize')),
                total : 0,
                dialogFormVisible: false,
                editType : 0,   //更改信息/创建商品
                editForm: {},     //更改信息的弹窗信息
            }
        },
        computed: {
            createStartTime(){
                if(this.searchData.createTime instanceof Array){
                    return this.searchData.createTime[0];
                }else{
                    return "";
                }
                    
            },
            CreateEndTime(){
                if(this.searchData.createTime instanceof Array){
                    return this.searchData.createTime[1];
                }else{
                    return "";
                }
            },
            updateStartTime(){
                if(this.searchData.updateTime instanceof Array){
                    return this.searchData.updateTime[0];
                }else{
                    return "";
                }
            },
            updateEndTime(){
                if(this.searchData.updateTime instanceof Array){
                    return this.searchData.updateTime[1];
                }else{
                    return "";
                }
            }
        },
        created(){
            this.getData();  //获取列表数据
        },
        mounted(){
            
        },
        methods: {
            resetForm(formName){
                this.$refs[formName].resetFields();
            },
            submitForm(formName){
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.getData();
                    } else {
                        return false;
                    }
                });
            },
            checkDetail(data){
                this.$router.push({ path: '/goodsPoolDetail', query: { id: data }})
            },
            getData(){
                this.$axios
                    .post("/admin/virtualGoods/queryList.json",{
                        goodId: this.searchData.id,
                        goodName: this.searchData.name,
                        goodStatus: this.searchData.status,
                        goodBelong: this.searchData.belong,
                        createStartTime: this.createStartTime,
                        createEndTime: this.CreateEndTime,
                        updateStartTime: this.updateStartTime,
                        updateEndTime: this.updateEndTime,
                        pageNo: this.current,
                        pageSize: this.pageSize
                    })
                    .then(res => {
                        const data = res.data;
                        if(data.success){
                            this.dataList = data.list;
                            if(data.pageInfo){
                                //获取分页信息
                                this.current = data.pageInfo.pageIndex;
                                this.total = data.pageInfo.recordCount;
                            }
                            //获取数据合并后的id集合
                            this.checkedGameId = this.dataList.map(e => e.id);
                            if(this.dataList && this.dataList.length<=0){
                                this.oneStatus = 0;
                            }else{
                            this.oneStatus = this.dataList[0].oneStatus;
                            }
                        }else{
                            this.$message.error(data.message);
                        } 
                    })
            },
            updateAll(status){
                const statusText = this.searchData.statusList[status];
                this.$confirm(`是否${statusText}全部商品？`, '提示', {
                    type: 'info'
                }).then(()=>{
                    this.$axios
                        .post("/admin/virtualGoods/updateOneStatus.json",{
                            oneStatus: status
                        })
                        .then(res => {
                            const data = res.data;
                            if(data.success){
                                this.$message.success("一键操作成功！");
                                this.getData();
                            }else{
                                this.$message.error(data.message);
                            } 
                        })
                }).catch(()=>{
                    
                })
            },
            //列表中选择框的点击事件
            handleSelectionChange(val){
                const checkedCount = val.length;   //所选择的条数
                const dataLength = this.dataList.length;   //总条数
                this.checkAll = dataLength == checkedCount;
                this.isIndeterminate = checkedCount > 0 && checkedCount < dataLength;
            },
            //全选按钮点击事件
            handleCheckAllChange(val){
                this.checkedData = val ? this.checkedGameId : [];
                this.isIndeterminate = false;
            },
            operationBtn(ids,status){
                if(ids.length == 0){
                    this.$message.error('请选择数据！');
                    return;
                }
                const idsArr = this.util.fnNumber.tranString(ids);    //转换为数组格式
                const statusText = this.searchData.statusList[status];
                this.$confirm(`是否对该商品进行${statusText}操作？`, '提示', {
                    type: 'info'
                }).then(()=>{
                    this.$axios
                        .post("/admin/virtualGoods/updateStatus.json",{
                            ids: idsArr,
                            status : status
                        })
                        .then(res => {
                            const data = res.data;
                            if(data.success){
                                this.$message.success("操作成功！");
                                this.getData();
                            }else{
                                this.$message.error(data.message);
                            } 
                        })
                }).catch(()=>{
                    
                })
            },
            editInfo(type,data){
                this.editType = type;
                this.editForm = type == 0 ? {} : JSON.parse(JSON.stringify(data));
                this.dialogFormVisible = true;
            },
            closeEdit(){
                this.$refs['ruleEditForm'].resetFields();    //初始化表单验证
            },
            submitEdit(formName){
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.$axios
                            .post("/admin/virtualGoods/saveOrUpdate.json",{
                                id: this.editForm.id,
                                code: this.editForm.code,
                                name: this.editForm.name,
                                shopMoney: this.editForm.shopMoney,
                                salePrice: this.editForm.salePrice,
                                belong: this.editForm.belong  
                            })
                            .then(res => {
                                debugger
                                const data = res.data;
                                if(data.success){
                                    this.$message.success("操作成功！");
                                    this.dialogFormVisible = false;
                                    this.getData();
                                }else{
                                    this.$message.error(data.message);
                                } 
                            })
                    } else {                        
                        return false;
                    }
                });
            },
            checkArea(productId){
                this.$router.push({ path: '/ascriptionCity', query: { productId: productId }});
            }
        }
    }

</script>


<style scoped>
    .createBtn{
        float: right;
        margin-top: -6.5px;
        margin-right: 10px;
    }
    .dialogInput{
        width: 250px;
    }
</style>
